<template>
  <view class="registration-success">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#FFFFFF"></u-icon>
      </view>
      <view class="navbar-title">求职报名</view>
      <view class="navbar-right">
      </view>
    </view>
    
    <!-- 成功提示区域 -->
    <view class="success-section">
      <view class="success-icon">
        <u-icon name="checkbox-mark" size="40" color="var(--u-primary)"></u-icon>
      </view>
      <text class="success-text">恭喜您,报名成功!</text>
      

    </view>
    

    
    <!-- 岗位信息卡片 -->
    <view class="job-info-card">
      <view class="info-item">
        <text class="info-label">报名企业</text>
        <text class="info-value">{{ signup.company }}<text v-if="signup.position"> / {{ signup.position }}</text></text>
      </view>
      <view class="info-item">
        <text class="info-label">工价</text>
        <text class="info-value">{{ signup.salary || '—' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">面试地址</text>
        <text class="info-value">{{ signup.detailAddress || signup.address || '—' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">到厂方式</text>
        <text class="info-value">{{ signup.arrivalMethod || '—' }}</text>
      </view>
      
      <!-- 卡片内操作按钮 -->
      <view class="card-actions">
        <button  class="action-btn invite-btn" @click="shareInvite" open-type="share">
          <text class="btn-text" >邀请好友赚钱</text>
        </button >
        <view class="action-btn service-btn" @click="shareService">
          <u-icon name="chat" size="16" color="#FFFFFF"></u-icon>
          <text class="btn-text">咨询客服</text>
          <text class="btn-subtitle">(了解面试事项)</text>
        </view>
      </view>
    </view>
    
    <!-- 免责声明 -->
    <view class="disclaimer">
      <text class="disclaimer-text">
        <text class="asterisk">*</text>由于工价波动原因,本报名记录仅当日有效,请准时前往企业面试!
      </text>
    </view>
    
    <!-- 地图区域 -->
    <view class="map-section">
      <view class="map-info" v-if="false">
        <text class="map-distance">{{ signup.address || '地址信息' }}</text>
        <text class="map-company">{{ signup.company || '企业名称' }}</text>
      </view>
	  <view class="map-container">
      <map 
        v-if="mapLocation.latitude && mapLocation.longitude"
        :latitude="mapLocation.latitude" 
        :longitude="mapLocation.longitude"
        :markers="mapMarkers"
        :scale="15"
        class="company-map"
        show-location
        @tap="openCompanyNavigation"
      >
        <view class="map-provider">
          <text class="provider-text">腾讯地图</text>
          <text class="copyright"></text>
        </view>
      </map>
      <view v-else class="map-placeholder">
        <text class="placeholder-text">暂无企业地址信息</text>
      </view>
	  </view>
    </view>
    
    <!-- 面试详情 -->
    <view class="interview-details" v-if="false">
      <view class="detail-item">
        <text class="detail-label">面试企业:</text>
        <text class="detail-value">{{ signup.company || '企业名称' }}</text>
      </view>
      <view class="detail-item">
        <text class="detail-label">面试地址:</text>
        <text class="detail-value">{{ signup.detailAddress || signup.address || '地址信息' }}</text>
      </view>
      <view class="detail-item">
        <text class="detail-label">到厂方式:</text>
        <text class="detail-value">{{ signup.arrivalMethod || '自行到厂' }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { systemApi, jobApi } from '@/api/api-helper.js'
import { useUserStore } from '@/stores/userStore'
import { userApi } from '@/api/api-helper.js'

const signup = ref({
  company: '',
  position: '',
  salary: '',
  arrivalMethod: '',
  address: '',
  detailAddress: '',
  recruitUseId: '',
  recruitUseEntryId: ''
})

// 地图位置信息
const mapLocation = ref({
  latitude: 30.51667,
  longitude: 114.31667
})

// 地图标记点
const mapMarkers = ref([])

const userStore = useUserStore()

onMounted(() => {
  // 初始化用户存储
  userStore.initFromCache()
  
  // 检查页面来源，只有从求职报名信息确认页面跳转过来时才显示订阅通知
  const shouldShowSubscribe = checkPageSource()
  
  // 获取最新的报名信息
  fetchLatestSignupInfo()
  
  // 只有从求职报名信息确认页面跳转过来时才显示订阅确认弹窗
  if (shouldShowSubscribe) {
    setTimeout(() => {
      showSubscribeModal()
    }, 500)
  }
})

// 检查页面来源，判断是否应该显示订阅通知
const checkPageSource = () => {
  try {
    const pages = getCurrentPages()
    if (pages.length < 2) return false
    
    // 获取上一个页面的路径
    const previousPage = pages[pages.length - 2]
    const previousPagePath = previousPage.route || ''
    
    // 只有从求职报名信息确认页面跳转过来时才显示订阅通知
    // 求职报名信息确认页面的路径通常是 /pages/job-application/job-application
    return previousPagePath.includes('job-application')
  } catch (error) {
    console.warn('检查页面来源失败:', error)
    return false
  }
}

// 获取最新的报名信息
const fetchLatestSignupInfo = async () => {
  try {
    // 优先从页面参数获取真实数据
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.options || {}
    const decodedData = JSON.parse(decodeURIComponent(options.data))
    if (decodedData.recruitUseId && decodedData.recruitUseEntryId) {
      // 如果有招聘ID，从接口获取最新的报名信息
      await fetchSignupInfoFromAPI(decodedData.recruitUseId, decodedData.recruitUseEntryId)
    } else if (decodedData.hireRecruitUseId && decodedData.hireRecruitUseEntryId) {
      // 兼容不同的参数名称
      await fetchSignupInfoFromAPI(decodedData.hireRecruitUseId, decodedData.hireRecruitUseEntryId)
    } else {
      // 如果没有页面参数，尝试从本地存储读取
      const data = uni.getStorageSync('last_signup')
      if (data) {
        signup.value = data
      }
    }
  } catch (e) {
    console.warn('读取报名信息失败', e)
    // 如果都失败了，尝试从本地存储读取
    try {
      const data = uni.getStorageSync('last_signup')
      if (data) {
        signup.value = data
      }
    } catch (storageError) {
      console.warn('读取本地存储失败', storageError)
    }
  }
}

// 从接口获取报名信息
const fetchSignupInfoFromAPI = async (recruitUseId: string, recruitUseEntryId: string) => {
  try {
    const openId = userStore.getOpenId()
    if (!openId) {
      console.warn('用户openId不存在')
      return
    }
    
    // 调用接口获取招聘信息详情
    const result = await jobApi.getHireRecruitUseById(recruitUseId, openId)
    
    if (result && result.code === 200 && result.data) {
      const jobData = result.data
      console.log('从接口获取的招聘信息:', jobData)
      
      // 更新报名信息
      signup.value = {
        company: jobData.customerName || '',
        position: jobData.positionName || '',
        salary: jobData.workPrice ? `${jobData.workPrice}` : '面议',
        arrivalMethod: jobData.arrivalMethod || '自行到厂',
        address: jobData.address || '',
        detailAddress: jobData.detailAddress || '',
        recruitUseId: recruitUseId,
        recruitUseEntryId: recruitUseEntryId
      }
      
      // 更新地图位置信息（如果有经纬度信息）
      if (jobData.longitude && jobData.latitude) {
        mapLocation.value = {
          latitude: jobData.latitude,
          longitude: jobData.longitude
        }
        
        // 设置地图标记点
        setMapMarkers()
      }
      
      // 保存到本地存储作为备份
      uni.setStorageSync('last_signup', signup.value)
    }
  } catch (error) {
    console.error('从接口获取报名信息失败:', error)
    // 如果接口调用失败，尝试从本地存储读取
    const data = uni.getStorageSync('last_signup')
    if (data) {
      signup.value = data
    }
  }
}

// 设置地图标记点
const setMapMarkers = () => {
  if (mapLocation.value.latitude && mapLocation.value.longitude) {
    // 企业位置标记点
    const companyMarker = {
      id: 1,
      longitude: mapLocation.value.longitude,
      latitude: mapLocation.value.latitude,
      title: signup.value.company || '企业位置',
      iconPath: '/static/icon/location-company.png', // 企业位置图标
      width: 32,
      height: 32
    }
    
    mapMarkers.value = [companyMarker]
    console.log('设置地图标记点成功:', companyMarker)
  }
}

// 打开企业导航
const openCompanyNavigation = () => {
  // 检查是否有企业位置信息
  if (!signup.value.address && !signup.value.detailAddress) {
    uni.showToast({
      title: '暂无企业地址信息',
      icon: 'none'
    })
    return
  }
  
  // 构建企业地址
  const companyAddress = signup.value.detailAddress || signup.value.address || ''
  const companyName = signup.value.company || '企业位置'
  
  // 使用微信小程序的导航接口
  uni.openLocation({
    latitude: mapLocation.value.latitude,
    longitude: mapLocation.value.longitude,
    name: companyName,
    address: companyAddress,
    scale: 15,
    success: () => {
      console.log('导航页面打开成功')
    },
    fail: (err) => {
      console.error('打开导航失败:', err)
      // 如果openLocation失败，尝试使用chooseLocation
      uni.showModal({
        title: '导航提示',
        content: '是否使用地图选择位置进行导航？',
        success: (res) => {
          if (res.confirm) {
            chooseLocationForNavigation()
          }
        }
      })
    }
  })
}

// 选择位置进行导航（备用方案）
const chooseLocationForNavigation = () => {
  uni.chooseLocation({
    success: (res) => {
      console.log('选择位置成功:', res)
      // 用户选择了位置，可以再次尝试打开导航
      uni.openLocation({
        latitude: res.latitude,
        longitude: res.longitude,
        name: res.name || '选择的位置',
        address: res.address || '',
        scale: 15
      })
    },
    fail: (err) => {
      console.error('选择位置失败:', err)
      uni.showToast({
        title: '选择位置失败',
        icon: 'none'
      })
    }
  })
}

const goBack = () => {
  uni.switchTab({ url: '/pages/jobs/jobs' })
}

const viewRecord = () => {
  uni.showToast({
    title: '查看报名记录',
    icon: 'none'
  })
}

// 分享邀请好友赚钱
const shareInvite = () => {
  // 调用分享功能，直接分享本小程序
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 5, // 5表示分享小程序
    path: '/pages/index/index', // 分享到首页
    query: 'from=invite', // 传递来源参数
    title: '邀请好友赚钱，一起找工作！',
    summary: '我正在使用这个求职平台，邀请你也来试试！',
    imageUrl: '/static/logo.png',
    success: function (res) {
      console.log('分享成功:', res)
      uni.showToast({
        title: '分享成功！',
        icon: 'success'
      })
    },
    fail: function (err) {
      console.error('分享失败:', err)
      uni.showToast({
        title: '分享失败，请重试',
        icon: 'none'
      })
    }
  })
}

// 分享咨询客服
const shareService = () => {
  // 调用分享功能，直接分享本小程序
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 5, // 5表示分享小程序
    path: '/pages/index/index', // 分享到首页
    query: 'from=service', // 传递来源参数
    title: '求职咨询客服',
    summary: '需要了解面试事项？点击咨询客服！',
    imageUrl: '/static/logo.png',
    success: function (res) {
      console.log('分享成功:', res)
      uni.showToast({
        title: '分享成功！',
        icon: 'success'
      })
    },
    fail: function (err) {
      console.error('分享失败:', err)
      uni.showToast({
        title: '分享失败，请重试',
        icon: 'none'
      })
    }
  })
}

// 显示订阅确认弹窗
const showSubscribeModal = () => {
  uni.showModal({
    title: '接收报名成功通知',
    content: '为了及时通知您面试相关事项，建议开启消息订阅',
    confirmText: '同意开启',
    cancelText: '暂不开启',
    success: async (res) => {
      if (res.confirm) {
        // 用户点击确定，调用微信订阅消息接口
		const data = await userApi.getSubscribeTemplate();
		console.log('绝地反击甲方',data)
        try {
          uni.requestSubscribeMessage({
            tmplIds: data?.data || [],
            success: async (subscribeRes) => {
              console.log('订阅消息结果:', subscribeRes)
                // 用户同意订阅，调用后端接口保存授权信息
                await saveSubscribeTemplate()
                uni.showToast({
                  title: '订阅成功！',
                  icon: 'success'
                })
            },
            fail: (err) => {
              console.error('订阅消息失败:', err)
              uni.showToast({
                title: '订阅失败，请重试',
                icon: 'none'
              })
            }
          })
        } catch (error) {
          console.error('处理订阅确认失败:', error)
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 保存订阅模板信息到后端
const saveSubscribeTemplate = async () => {
  try {
    // 获取用户openId
    const openId = userStore.getOpenId()
    if (!openId) {
      console.warn('用户openId不存在')
      return
    }
    
    // 检查必要的参数
    if (!signup.value.recruitUseId || !signup.value.recruitUseEntryId) {
      console.warn('招聘信息不完整')
      return
    }
    
    const data = {
      recruitUseId: signup.value.recruitUseId,
      recruitUseEntryId: signup.value.recruitUseEntryId,
      openId: openId,
      templateId: ['uxiPCGh5xq25qBIKZwaWP2molNKz-MxAe36GbUpGz1M']
    }
    
    const result = await systemApi.saveSubscribeTemplate(data)
    if (result.code === 200) {
      console.log('保存订阅模板成功')
    } else {
      console.warn('保存订阅模板失败:', result.msg)
    }
  } catch (error) {
    console.error('保存订阅模板失败:', error)
  }
}

const getReport = () => {
  uni.showToast({
    title: '获得面试评测报告',
    icon: 'none'
  })
}
</script>

<style lang="scss" scoped>
.registration-success {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-top: env(safe-area-inset-top);
}

// 顶部导航栏
.navbar {
  background-color: var(--u-primary);
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  padding-top: calc(env(safe-area-inset-top) + 80rpx);
  position: relative;
}

.navbar-left,
.navbar-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 36rpx;
  color: #FFFFFF;
  font-weight: 500;
}

// 成功提示区域
.success-section {
  background-color: var(--u-primary);
  padding: 60rpx 30rpx;
  padding-top: calc(60rpx + env(safe-area-inset-top));
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  width: 80rpx;
  height: 80rpx;
  background-color: #FFFFFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.success-text {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: 500;
}



// 岗位信息卡片
.job-info-card {
  background-color: #FFFFFF;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 30rpx;
  }
}

.info-label {
  font-size: 28rpx;
  color: #999;
  width: 260rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
  text-align: right;
  
}

// 卡片内操作按钮
.card-actions {
  display: flex;
  gap: 20rpx;
  border-top: 1rpx solid #EEEEEE;
  padding-top: 30rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 0;
}

.invite-btn {
  background-color: #FFFFFF;
  border: 2rpx solid var(--u-primary);
}

.service-btn {
  background-color: var(--u-primary);
  flex-direction: row;
  gap: 4rpx;
}

.btn-text {
  font-size: 26rpx;
  color: var(--u-primary);
  font-weight: 500;
}

.service-btn .btn-text {
  color: #FFFFFF;
}

.btn-subtitle {
  font-size: 20rpx;
  color: #FFFFFF;
  opacity: 0.8;
}

// 免责声明
.disclaimer {
  margin: 0 20rpx 20rpx;
}

.disclaimer-text {
  font-size: 24rpx;
  color: #666666;
  line-height: 1.4;
}

.asterisk {
  color: var(--u-primary);
}

// 地图区域
.map-section {
  background-color: #FFFFFF;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 20rpx;
}

.map-info {
  margin-bottom: 20rpx;
}

.map-distance {
  font-size: 28rpx;
  color: #333333;
  display: block;
  margin-bottom: 8rpx;
}

.map-company {
  font-size: 26rpx;
  color: #666666;
  display: block;
  margin-bottom: 4rpx;
}

.map-container {
  position: relative;
  height: 300rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.company-map {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.map-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.placeholder-text {
  font-size: 24rpx;
  color: #999999;
}

.map-text {
  font-size: 24rpx;
  color: #999999;
}

.map-provider {
  position: absolute;
  bottom: 10rpx;
  left: 10rpx;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.provider-text {
  font-size: 20rpx;
  color: #666666;
}

.copyright {
  font-size: 18rpx;
  color: #999999;
}

// 面试详情
.interview-details {
  background-color: #FFFFFF;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.detail-label {
  font-size: 28rpx;
  color: #333333;
  min-width: 200rpx;
}

.detail-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
  text-align: right;
}

// 查看报名记录详情按钮
.view-record-btn {
  margin: 0 20rpx 20rpx;
}



// 测算面试通过率卡片
.rate-card {
  background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.rate-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.rate-text {
  flex: 1;
}

.rate-title {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: 600;
  display: block;
  margin-bottom: 8rpx;
}

.rate-subtitle {
  font-size: 24rpx;
  color: #FFFFFF;
  opacity: 0.9;
}

.rate-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rate-btn {
  width: 100%;
}
</style> 